package com.mzy.tomcat.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class MzyHttpRequest {

    private InputStream inputStream;

    private String uri;
    // 请求方法
    private String method;
    // 请求参数
    private Map<String, Object> parameters = new HashMap<>();

    private String url;

    public MzyHttpRequest(InputStream inputStream) throws IOException {
        this.init(inputStream);
    }

    public void init(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String requestHeader = "";
        if ((requestHeader = bufferedReader.readLine()) != null) {
            // GET /mizeyu? HTTP/1.1
            // 解析请求头
            String[] requestHeaderFirstLine = requestHeader.split(" ");
            this.method = requestHeaderFirstLine[0].toUpperCase();

            // 分割url地址和请求参数
            this.url = requestHeaderFirstLine[1];
            String[] uriAndParameters = url.split("\\?");

            this.uri = uriAndParameters[0];
            // 是否有请求参数 防止下标越界
            if (uriAndParameters.length > 1 && !"".equals(uriAndParameters[1])) {
                // 解析请求参数
                String[] params = uriAndParameters[1].split("&");
                for (String param : params) {
                    String[] paramPair = param.split("=");
                    if (paramPair.length > 1) {
                        parameters.put(paramPair[0], paramPair[1]);
                    }
                }
            }
        }
    }


    public Object getAttribute(String name) {
        return parameters.get(name);
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }
}
